package com.itstyle.seckill.common.utils;

import java.util.ArrayList;
import java.util.List;

public class MyContainerWaitNotify {
    volatile List list = new ArrayList();
    public void add(Object o) {
        list.add(o);
    }
    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        MyContainerWaitNotify mcwn = new MyContainerWaitNotify();
        final Object lock = new Object();
        new Thread(()->{
            synchronized (lock) {
                System.out.print(" ***线程t2启动*** ");
                if (mcwn.size() != 5) {
                    try {
                        lock.wait();  //size不等于5时，就一直在那等着，直到被t1叫醒
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(" ***线程t2结束*** ");
                lock.notify();  //通知t1继续执行
            }
        }, "t2").start();

        new Thread(()->{
            synchronized (lock) {
                for(int i=0; i<10; i++) {
                    mcwn.add(new Object());
                    System.out.print(" add-"  + i);
                    if (mcwn.size() == 5) {
                        lock.notify();  //唤醒另一个线程t2，本线程继续执行，直至synchronized包裹的代码块结束或者调用了wait
                        try {
                            lock.wait(); //释放锁，让t2得以执行
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t1").start();
    }
}